package whisper.api.gateway.frame.auth.repository;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import whisper.api.gateway.frame.auth.config.DbConfig;
import whisper.api.gateway.frame.auth.domain.User;

/**
 * Created by JT on 2017/9/22.
 */
@Repository
public class UserRepositoryImpl implements UserRepository {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User findUserByUsername(String username) {
        String[] columnArr = DbConfig.TABLE_COLUMNS_USER;
        columnArr[3] = "date_format(CREATE_TIME,'%Y-%m-%d %H:%i:%S') AS CREATE_TIME";
        columnArr[4] = "date_format(LAST_LOGIN_TIME,'%Y-%m-%d %H:%i:%S') AS LAST_LOGIN_TIME";
        String sql = String.format("SELECT %s FROM %s WHERE USERNAME=?",
                String.join(",", columnArr), DbConfig.TABLE_NAME_USER);
        Object[] params = new Object[]{username};

        User user = jdbcTemplate.queryForObject(sql, params, new BeanPropertyRowMapper<User>(User.class));
        return user;
    }

    @Override
    public void insertUser(User user) {
        String[] tableColumns = (String[]) ArrayUtils.remove(DbConfig.TABLE_COLUMNS_USER, 0);
        String columns = String.join(",", tableColumns);
        String sql = String.format("INSERT INTO %s(%s) VALUES(?, ?, ?, ?, ?, ?, ?)", DbConfig.TABLE_NAME_USER, columns);
        Object[] params = new Object[]{ user.getUsername(), user.getPassword(),
                        user.getCreateTime(), user.getLastLoginTime(), user.getIsAvailable(),
                        user.getIsOverdue(), user.getIsLock()};
        jdbcTemplate.update(sql, params);
    }

    @Override
    public void addRoleToUser(Integer uid, Integer rid) {
        String columns = String.join(",", DbConfig.TABLE_COLUMNS_USER_ROLE);
        String sql = String.format("INSERT INTO %s(%s) VALUES(?, ?)",
                DbConfig.TABLE_NAME_USER_ROLE, columns);
        Object[] params = new Object[]{uid, rid};
        jdbcTemplate.update(sql, params);
    }


}
